<?php
/**
 * K780通用SDK
 *
 * @author      朱君无 <bedlate@gmail.com>
 * @link        http://www.k780.com/
 * @license     http://zhujunwu.cn/#footer
 * @version     0.0.1
 * 
 */
class K780 {

    static private $config = array(
        'url' => 'http://api.k780.com:88/',
        'appkey' => '10003',
        'sign' => 'b59bc3ef6191eb9f747dd4e83c99f2a4',
        'format' => 'json'
    );

    static private $last_query = '';

    /**
     * [__construct 初始化默认配置]
     * @param array $config array('appkey' => 'xxxx', 'sign' => 'xxxxx')
     */
    function __construct($config = array()) {
        self::$config = array_merge(self::$config, $config);
    }

    /**
     * [query 查询]
     * @param  [type]  $data        [查询的数据，支持数组或字符串]
     * @param  boolean $parse_array [是否将查询结果转换为数组]
     * @param  integer $timeout     [客户端超时]
     * @param  string  $method      [请求方法]
     * @return [type]               [parse_array为TRUE则返回数组，否则返回data中的'format'格式]
     */
    function query($data, $parse_array = FALSE, $timeout = 10, $method = 'get') {
        $url = self::$config['url'];
        $data_arr = self::data_parse($data);
        $data_str = http_build_query($data_arr);
        $query_url = $url . '?' . $data_str;
        self::$last_query = $query_url;
        $contents = self::curl_get_contents($query_url, $timeout, $method);
        if ($parse_array) {
            $contents = self::str_to_array($contents, $data_arr['format']);
        }
        return $contents;
    }

    /**
     * [config 获取配置]
     * @return [array] [description]
     */
    function config($name = NULL) {
        if (is_string($name) && isset(self::$config[$name])) {
            return self::$config[$name];
        } elseif (is_array($name)) {
            foreach ($name as $key => $value) {
                self::$config[$key] = $value;
            }
        } else {
            return self::$config;
        }
    }

    /**
     * [last_query 获取最后一次查询语句的数据]
     * @return [string] [description]
     */
    function last_query() {
        return self::$last_query;
    }

    /**
     * [data_parse 数据转换]
     * @param  [type] $data [要转换的数据，支持数组与字符串]
     * @return [string]       [URL query string]
     */
    static private function data_parse($data) {
        $array = array(
            'appkey' => self::$config['appkey'],
            'sign' => self::$config['sign'],
            'format' => self::$config['format']
        );
        if (is_string($data)) {
            $data = trim(ltrim($data, '?'));
            parse_str($data, $output);
        } elseif (is_array($data)) {
            $output = $data;
        }
        $array = array_merge($array, $output);
        return $array;
    }

    /**
     * [str_to_array 字符串转换为数组]
     * @param  [type] $str    [要转换字符串]
     * @param  string $format [字符串类型，json或XML]
     * @return [type]         [description]
     */
    static private function str_to_array($str, $format = 'json') {
        switch (strtolower($format)) {
            case 'json':
                $str = preg_replace('/^[\s\S]+\(/U', '', $str);
                $str = rtrim($str, ')');
                $str = json_decode($str, TRUE);
                break;
            case 'xml':
                $str = json_decode(json_encode(simplexml_load_string($str)), TRUE);
                break;
        }
        return $str;
    }

    /**
     * [curl_get_contents 封装curl]
     * @param  [type]  $url     [description]
     * @param  integer $timeout [description]
     * @param  string  $method  [description]
     * @return [type]           [description]
     */
    static private function curl_get_contents($url, $timeout = 10, $method = 'get') {
        if (function_exists('curl_init')) {
            $curlHandle = curl_init();
            curl_setopt($curlHandle, CURLOPT_URL, $url);
            curl_setopt($curlHandle, CURLOPT_HEADER, FALSE);
            curl_setopt($curlHandle, CURLOPT_NOBODY, FALSE);
            curl_setopt($curlHandle, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, TRUE);
            curl_setopt($curlHandle, CURLOPT_MAXREDIRS, 10);
            curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
            // curl_setopt($curlHandle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.0)");
            if ('post' === strtolower($method)) {
                curl_setopt($curlHandle, CURLOPT_POST, 1);
            }
            $result = curl_exec($curlHandle);
            if (curl_errno($curlHandle)) {
                $result .= curl_error($curlHandle);
            }
            curl_close($curlHandle);
        } else {
            $ctx = stream_context_create(array(
                'http' => array(
                    'method' => "GET",
                    'header' => "Content-Type: text/html; charset=utf-8",
                    'timeout' => $timeout
                )
            ));
            $result = file_get_contents($url, 0, $ctx);
        }
        return $result;
    }

}
